package com.fulihui.information.biz.content.impl;

import com.fulihui.information.biz.content.ContentCommentsBizManager;
import com.fulihui.information.biz.content.ContentCommentsReplyBizManager;
import com.fulihui.information.biz.content.impl.handler.ContentCommentsHandler;
import com.fulihui.information.core.repository.ContentCommentsReplyRepository;
import com.fulihui.information.core.repository.ContentCommentsRepository;
import com.fulihui.information.dal.dataobj.InfoContentCommentsReply;
import com.fulihui.information.dal.dataobj.InfoContentCommentsReplyExample;
import com.fulihui.information.dto.InfoContentCommentsReplyDTO;
import com.fulihui.information.enums.ECommentsStatus;
import com.fulihui.information.request.ContentCommentsReplyCreateRequest;
import com.fulihui.information.request.ContentCommentsReplyQueryRequest;
import com.fulihui.integralbusiness.constants.IntegralBusinessFlags;
import com.fulihui.integralbusiness.producer.ZbusIntegralCreator;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import org.near.dal.sequence.SeqKit;
import org.near.toolkit.common.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.fulihui.information.enums.ECommentsStatus.CHECK;
import static com.fulihui.information.enums.ECommentsStatus.UNCHECK;

/**
 * Created by LM on 2017/4/9.
 */
@Component
public class ContentCommentsReplyBizManagerImpl implements ContentCommentsReplyBizManager {

    @Autowired
    private ContentCommentsReplyRepository commentsReplyRepository;
    @Autowired
    private ContentCommentsBizManager      commentsBizManager;
    @Autowired
    private ZbusIntegralCreator            zbusIntegralCreator;
    @Autowired
    private ContentCommentsHandler         commentsHandler;
    @Autowired
    private TransactionTemplate            transactionTemplate;
    @Autowired
    private ContentCommentsRepository      commentsRepository;

    @Override
    public String createComments(ContentCommentsReplyCreateRequest request) {
        InfoContentCommentsReply commentsReply = new InfoContentCommentsReply();
        BeanUtils.copyProperties(request, commentsReply);
        // 默认未审核
        commentsReply.setStatus(ECommentsStatus.UNCHECK.getCode());
        // 生成序列id
        commentsReply.setId(SeqKit.genId() + "");
        // 回复内容编码
        commentsReply.setReplyContent(Base64.encodeBase64String(request.getCommentContent()
            .getBytes()));
        // 设置内容标题
        commentsReply.setContentTitle(commentsBizManager.getContentTitle(request.getContentId(),
            request.getContentTitle()));
        final boolean[] result = { true };
        result[0] = transactionTemplate.execute(status -> {
            // 创建回复
            result[0] = commentsReplyRepository.create(commentsReply);
            if (result[0]) {
                // 叠加回复数
                result[0] = commentsRepository.replyTotalAdd(commentsReply.getCommentId());
            }
            if (!result[0]) {
                status.setRollbackOnly();
            }
            return result[0];
        });
        if (result[0]) {
            try {
                /**
                 * 积分返利
                 */
                Map<String, Object> msg = Maps.newHashMap();
                msg.put("userId", request.getUserId());
                msg.put("commentsId", commentsReply.getId());
                zbusIntegralCreator.create(IntegralBusinessFlags.COMMENTS, msg);
                /**
                 * 发送消息
                 */
                commentsHandler.sendCommentsMessage(commentsReply);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
        return commentsReply.getId();
    }

    @Override
    public List<InfoContentCommentsReplyDTO> queryPage(ContentCommentsReplyQueryRequest request) {
        InfoContentCommentsReplyExample example = genExample(request);
        if (StringUtil.isNotBlank(request.getOrderByClause())) {
            example.setOrderByClause(request.getOrderByClause());
        }
        example.setLimit(request.getRows());
        example.setOffset(request.start4Mysql());
        return commentsReplyRepository.queryPage(example);
    }

    @Override
    public List<InfoContentCommentsReplyDTO> queryPageExt(ContentCommentsReplyQueryRequest request,
                                                          boolean onOff) {
        InfoContentCommentsReplyExample example = genExampleExt(request, onOff);
        if (StringUtil.isNotBlank(request.getOrderByClause())) {
            example.setOrderByClause(request.getOrderByClause());
        }
        example.setLimit(request.getRows());
        example.setOffset(request.start4Mysql());
        return commentsReplyRepository.queryPage(example);
    }

    @Override
    public long countByExample(ContentCommentsReplyQueryRequest request) {
        InfoContentCommentsReplyExample example = genExample(request);
        return commentsReplyRepository.countByExample(example);
    }

    @Override
    public long countByExampleExt(ContentCommentsReplyQueryRequest request, boolean onOff) {
        InfoContentCommentsReplyExample example = genExampleExt(request, onOff);
        return commentsReplyRepository.countByExample(example);
    }

    private InfoContentCommentsReplyExample genExample(ContentCommentsReplyQueryRequest request) {
        InfoContentCommentsReplyExample example = new InfoContentCommentsReplyExample();
        InfoContentCommentsReplyExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(request.getCommentsId())) {
            criteria.andCommentIdEqualTo(request.getCommentsId());
        }
        if (!CollectionUtils.isEmpty(request.getCommentsIdList())) {
            criteria.andCommentIdIn(request.getCommentsIdList());
        }
        if (StringUtil.isNotBlank(request.getContentId())) {
            criteria.andContentIdEqualTo(request.getContentId());
        }
        if (StringUtil.isNotBlank(request.getUserId())) {
            criteria.andUserIdEqualTo(request.getUserId());
        }
        if (StringUtil.isNotBlank(request.getToUserId())) {
            criteria.andToUserIdEqualTo(request.getToUserId());
        }
        if (request.getStartDate() != null) {
            criteria.andGmtCreateGreaterThanOrEqualTo(request.getStartDate());
        }
        if (request.getEndDate() != null) {
            criteria.andGmtCreateLessThan(request.getEndDate());
        }
        if (!CollectionUtils.isEmpty(request.getStatus())) {
            criteria.andStatusIn(request.getStatus());
        }
        return example;
    }

    @Override
    public InfoContentCommentsReplyExample genExampleExt(ContentCommentsReplyQueryRequest request,
                                                         boolean onOff) {
        InfoContentCommentsReplyExample example = new InfoContentCommentsReplyExample();
        InfoContentCommentsReplyExample.Criteria criteria0 = example.createCriteria();
        if (StringUtil.isNotBlank(request.getCommentsId())) {
            criteria0.andCommentIdEqualTo(request.getCommentsId());
        }
        if (!CollectionUtils.isEmpty(request.getCommentsIdList())) {
            criteria0.andCommentIdIn(request.getCommentsIdList());
        }
        if (onOff) { // 开关启用，先显示后审核
            criteria0.andStatusIn(Arrays.asList(CHECK.getCode(), UNCHECK.getCode()));
        } else { // 开关关闭，先审核后显示 or 自己的评论
            // 已审核
            criteria0.andStatusEqualTo(CHECK.getCode());
            if (StringUtil.isNotBlank(request.getUserId())) {
                // or自己的评论
                InfoContentCommentsReplyExample.Criteria criteria1 = example.or();
                if (StringUtil.isNotBlank(request.getCommentsId())) {
                    criteria1.andCommentIdEqualTo(request.getCommentsId());
                }
                if (!CollectionUtils.isEmpty(request.getCommentsIdList())) {
                    criteria1.andCommentIdIn(request.getCommentsIdList());
                }
                criteria1.andStatusEqualTo(UNCHECK.getCode());
                criteria1.andUserIdEqualTo(request.getUserId());
            }
        }
        return example;
    }

    @Override
    public List<InfoContentCommentsReplyDTO> queryPageUserCommentsReply(ContentCommentsReplyQueryRequest request) {
        InfoContentCommentsReplyExample example = genExample(request);
        // 数据偏移量
        if (request.getNum() != null) {
            example
                .setOffset(request.start4Mysql() - request.getNum() > 0 ? request.start4Mysql()
                                                                          - request.getNum() : 0);
        } else {
            example.setOffset(request.start4Mysql());
        }
        example.setLimit(request.getRows());
        example.setOrderByClause(request.getOrderByClause());
        return commentsReplyRepository.queryPage(example);
    }

}
